<template>
  <div class="container">
    <van-nav-bar
      :title="userInfo.regStatus == 4 ? '资料修改' : '商户入网'"
      right-text="保存"
      left-arrow
      @click-left="goBack"
      @click-right="noSave"
    />
    <div class="content-box">
      <Remarks v-if="userInfo.regStatus == 4" :contents="userInfo.remarks" />
      <!-- 步骤条 -->
      <Steps
        :dataSource="
          formData.openType == 1
            ? [
                { name: '基本信息', checked: true },
                { name: '附件信息', checked: true },
              ]
            : [
                { name: '基本信息', checked: true },
                { name: '结算信息', checked: true },
                { name: '费率信息', checked: true },
                { name: '附件信息', checked: true },
              ]
        "
      />
      <van-form
        scroll-to-error
        input-align="right"
        ref="form"
        @submit="nextStep"
      >
        <van-field
          class="mt-margin"
          name="storeAddressImgList"
          :rules="[{ validator, message: '请上传营业场所图片' }]"
          v-if="configEle.includes('eleStoreInsideImg')"
        >
          <template #label>
            <p class="attach-item-title">营业场所</p>
            <p class="placholder">请上传营业场所内景照</p>
            <p class="example" @click="lookExample(storeAddrImgExample)">
              查看示例&nbsp;
              <van-icon name="arrow" />
            </p>
          </template>
          <template #input>
            <UploaderImg
              v-model="storeAddressImgList"
              @uploadAfter="uploadStoreAddressImg"
              @beforeDelete="deleteStoreAddressImg"
            >
              <img
                class="preview-img"
                src="@/assets/store/store-addr-img.png"
                alt
              />
            </UploaderImg>
          </template>
        </van-field>
        <van-field
          class="mt-margin"
          name="storeDoorImgList"
          :rules="[{ validator, message: '请上传营业场所门头照' }]"
          v-if="configEle.includes('eleStoreGateImg')"
        >
          <template #label>
            <p class="attach-item-title">门头照</p>
            <p class="placholder">请上传营业场所门头照</p>
            <p class="example" @click="lookExample(doorImgExample)">
              查看示例&nbsp;
              <van-icon name="arrow" />
            </p>
          </template>
          <template #input>
            <UploaderImg
              v-model="storeDoorImgList"
              @uploadAfter="uploadStoreDoorImg"
              @beforeDelete="deleteStoreDoorImg"
            >
              <img class="preview-img" src="@/assets/store/door-img.png" alt />
            </UploaderImg>
          </template>
        </van-field>
        <van-field
          class="mt-margin"
          name="cashierImgList"
          :rules="[{ validator, message: '请上传收银台' }]"
          v-if="configEle.includes('eleStoreCashierImg')"
        >
          <template #label>
            <p class="attach-item-title">收银台</p>
            <p class="placholder">请上传收银台</p>
            <p class="example" @click="lookExample(cashierExample)">
              查看示例&nbsp;
              <van-icon name="arrow" />
            </p>
          </template>
          <template #input>
            <UploaderImg
              v-model="cashierImgList"
              @uploadAfter="uploadCashierImg"
              @beforeDelete="deleteCashierImg"
            >
              <img
                class="preview-img"
                src="@/assets/store/cashier-img.png"
                alt
              />
            </UploaderImg>
          </template>
        </van-field>
        <van-field
          class="mt-margin"
          name="proofImgList"
          :rules="[{ validator, message: '请上传关系证明材料' }]"
          v-if="configEle.includes('eleStoreRelationImg')"
        >
          <template #label>
            <p class="attach-item-title">商户关系证明</p>
            <p class="placholder">请上传关系证明材料</p>
            <p class="example" @click="lookExample(proogImgExample)">
              查看示例&nbsp;
              <van-icon name="arrow" />
            </p>
            <p class="example" @click="downloadExample">
              下载模板&nbsp;
              <van-icon name="arrow" />
            </p>
          </template>
          <template #input>
            <UploaderImg
              v-model="proofImgList"
              @uploadAfter="uploadProofImg"
              @beforeDelete="deleteProofImg"
            >
              <img class="preview-img" src="@/assets/store/proof-img.png" alt />
            </UploaderImg>
          </template>
        </van-field>
        <van-field
          class="mt-margin"
          name="proofHandImgList"
          :rules="[{ validator, message: '请上传法人手持商户关系证明' }]"
          v-if="configEle.includes('eleLegalStoreRelationImg')"
        >
          <template #label>
            <p class="attach-item-title">法人手持商户关系证明</p>
            <p class="placholder">请上传法人手持商户关系证明</p>
            <p class="example" @click="lookExample(cashierExample)">
              查看示例&nbsp;
              <van-icon name="arrow" />
            </p>
          </template>
          <template #input>
            <UploaderImg
              v-model="proofHandImgList"
              @uploadAfter="uploadProofHandImg"
              @beforeDelete="deleteProofHandImg"
            >
              <img class="preview-img" src="@/assets/store/cashier-img.png" />
            </UploaderImg>
          </template>
        </van-field>
        <van-field
          class="mt-margin"
          name="proofHandImgList"
          v-if="configEle.includes('eleOtherImg')"
        >
          <template #label>
            <p class="attach-item-title">辅助材料（非必填）</p>
            <p class="placholder">
              可上传辅助材料增加审 核成功率。例如：负责 人与门头合照、手持身
              份证等照片。
            </p>
          </template>
          <template #input>
            <UploaderImg
              v-model="assistImgList"
              :max-count="5"
              :multiple="true"
              @uploadAfter="uploadAssistImg"
              @beforeDelete="deleteAssistImg"
            >
              <img
                class="preview-img"
                src="@/assets/store/assist-img.png"
                alt
              />
            </UploaderImg>
          </template>
        </van-field>
        <van-field
          class="mt-margin"
          label="推荐人（非必填）"
          placeholder="请输入推荐人"
          name="acquiringPeople"
          v-model="formData.acquiringPeople"
          v-if="configEle.includes('eleAcquiringPeople')"
        />
        <van-field
          class="mt-margin"
          label="推荐经理（非必填）"
          placeholder="请输入推荐经理"
          name="acquiringManager"
          v-model="formData.acquiringManager"
          v-if="configEle.includes('eleAcquiringManager')"
        />
        <van-field
          class="mt-margin"
          label="备注（非必填）"
          placeholder="请输入备注"
          name="acquiringRemarks"
          v-model="formData.acquiringRemarks"
          v-if="configEle.includes('eleAcquiringRemarks')"
        />
        <van-button
          block
          type="info"
          color="#FFB72F"
          class="next-step-btn"
          native-type="submit"
          >下一步</van-button
        >
      </van-form>
    </div>
    <van-dialog
      v-model="showExample"
      title="查看示例"
      confirmButtonText="关闭"
      confirmButtonColor="#FFB72F"
    >
      <div class="example-container">
        <img :src="exampleImg" class="example-img" />
      </div>
    </van-dialog>
  </div>
</template>

<script>
import storeAddrImgExample from "@/assets/store/store-addr-img-example.png";
import doorImgExample from "@/assets/store/door-img-example.png";
import cashierExample from "@/assets/store/cashier-img-example.png";
import proogImgExample from "@/assets/store/proof-img-example.png";
import { savePicture } from "@/utils/utils.js";
import { save } from "@/api/stores";
import { getChannelTemplate } from "@/api/channel";
import { isBlacklist } from "@/api/merchant";

export default {
  name: "Step4",
  components: {
    HeaderComp: () => import("@/components/HeaderComps"),
    Remarks: () => import("@/components/Remarks"),
    Steps: () => import("@/components/steps"),
    UploaderImg: () => import("@/components/UploaderImg"),
  },
  data() {
    return {
      formData: {},
      proogImgExample,
      storeAddrImgExample,
      doorImgExample,
      exampleImg: "",
      cashierExample,
      showExample: false,
      storeAddressImgList: [],
      storeDoorImgList: [],
      cashierImgList: [],
      proofImgList: [],
      proofHandImgList: [],
      assistImgList: [],
    };
  },
  computed: {
    userInfo() {
      return this.$store.state.user.userInfo;
    },
    merchantForm() {
      return this.$store.state.merchant;
    },
    settlement() {
      return this.$store.state.settlement;
    },
    configEle() {
      console.log(
        "configEle",
        this.$store.state.common.config.map((item) => item.configEle)
      );
      return this.$store.state.common.config.map((item) => item.configEle);
    },
  },

  watch: {
    formData: {
      handler() {
        this.$store.commit("setAcquiring", {
          acquiringManager: this.formData.acquiringManager,
          acquiringPeople: this.formData.acquiringPeople,
          acquiringRemarks: this.formData.acquiringRemarks,
        });
      },
      deep: true,
    },
  },
  mounted() {
    if (this.merchantForm.storeAddressImg) {
      this.storeAddressImgList = [{ url: this.merchantForm.storeAddressImg }];
    }
    if (this.merchantForm.storeDoorImg) {
      this.storeDoorImgList = [{ url: this.merchantForm.storeDoorImg }];
    }
    if (this.merchantForm.cashierImg) {
      this.cashierImgList = [{ url: this.merchantForm.cashierImg }];
    }
    if (this.merchantForm.proofImg) {
      this.proofImgList = [{ url: this.merchantForm.proofImg }];
    }
    if (this.merchantForm.assistImg.length > 0) {
      this.assistImgList = this.merchantForm.assistImg;
    }
    if (this.merchantForm.proofHandImg) {
      this.proofHandImgList = [{ url: this.merchantForm.proofHandImg }];
    }
    let form = this.$store.state.merchant;
    let newForm = JSON.parse(JSON.stringify(form));
    this.formData = newForm;
    this.getChannelTemplateFun();
    window.scrollTo({
      left: 0,
      top: 0,
      behavior: "smooth",
    });
  },
  methods: {
    noSave() {
      this.$dialog
        .confirm({
          title: "商户认证",
          message: `确认是否保存资料？`,
          cancelButtonText: "取消",
          // cancelButtonColor: "#FFB72F",
          confirmButtonText: "确认",
          confirmButtonColor: "#FFB72F",
        })
        .then(() => {
          // 保存资料
          if (this.formData.openType) {
            this.$store.commit("setComplete", 0);
            this.$toast({
              type: "loading",
              message: "正在提交...",
              forbidClick: true,
              duration: 0,
            });
            save(this.$store.state)
              .then((res) => {
                // document.title = "提交成功";
                this.$toast.clear();
                if (res.code == 200) {
                  this.$toast({
                    type: "success",
                    message: "保存成功",
                    duration: 1500,
                  });
                  this.$store.dispatch("setSaved", true);
                } else {
                  this.$toast({
                    message: res.msg || "操作失败",
                    duration: 2000,
                    forbidClick: true,
                  });
                }
              })
              .catch((err) => {
                this.$toast.clear();
                // document.title = "返回APP";
              });
            // next();
          } else {
            document.title = "返回APP";
          }
        })
        .catch(() => {
          // 取消
          // document.title = "返回APP";
          // next();
        });
    },
    lookExample(url) {
      this.exampleImg = url;
      this.showExample = true;
    },
    nextStep() {
      Promise.all([
        this.isBlackListMethods(this.userInfo.storeMobile, "手机号"),
        this.isBlackListMethods(this.settlement.settlementNum, "结算人证件号"),
        this.isBlackListMethods(this.merchantForm.legalIdcard, "法人身份证号"),
      ]).then((arr) => {
        if (!arr.some((v) => v == true)) {
          this.$router.push({
            path: "/signature",
          });
        }
      });
    },
    onOversize() {
      this.$toast("图片过大无法上传\n请上传10MB以内的图片！");
    },
    deleteCashierImg(file) {
      this.$dialog
        .alert({
          title: "移除图片",
          message: "是否确定移除该图片？",
          closeOnClickOverlay: true,
          confirmButtonColor: "#FFB72F",
        })
        .then(() => {
          this.cashierImgList = [];
          this.$store.commit("PSetCashierImg", "");
        });
    },
    uploadCashierImg(link) {
      this.$store.commit("PSetCashierImg", link);
    },
    //营业场所照
    deleteStoreAddressImg(file) {
      this.storeAddressImgList = [];
      this.$store.commit("PSetStoreAddressImg", "");
    },
    uploadStoreAddressImg(link) {
      this.$store.commit("PSetStoreAddressImg", link);
    },
    //门头照
    deleteStoreDoorImg(file) {
      this.storeDoorImgList = [];
      this.$store.commit("PSetStoreDoorImg", "");
    },
    uploadStoreDoorImg(link) {
      this.$store.commit("PSetStoreDoorImg", link);
    },
    //关系证明
    deleteProofImg(file) {
      this.proofImgList = [];
      this.$store.commit("PSetProofImg", "");
    },
    uploadProofImg(link) {
      this.$store.commit("PSetProofImg", link);
    },
    //法人手持商户关系证明
    uploadProofHandImg(link) {
      this.$store.commit("PSetProofHandImg", link);
    },
    deleteProofHandImg(file) {
      this.proofHandImgList = [];
      this.$store.commit("PSetProofHandImg", "");
    },
    //辅助材料
    deleteAssistImg(linkList) {
      console.log(linkList);
      this.$store.commit("setAssistImg", linkList);
    },
    uploadAssistImg(linkList) {
      this.$store.commit("setAssistImg", linkList);
    },
    goBack() {
      this.$router.go(-1);
      // this.$router.push({
      //   path: "/submitInfo/step4",
      // });
    },
    // 下载模版
    // 下载模版
    downloadExample() {
      console.log(this.templateUrl);
      if (this.templateUrl) {
        savePicture(this.templateUrl);
      } else {
        this.$toast("模板获取失败，请联系客服");
      }
    },
    getChannelTemplateFun() {
      // 结算类型为非法对私 切开户类型不为
      const [acconutType, openType] = [
        Number(this.settlement.acconutType),
        Number(this.formData.openType),
      ];
      if (acconutType === 3 && openType !== 1) {
        console.log(this.merchantForm.channelCode);
        getChannelTemplate(this.merchantForm.channelCode).then((res) => {
          const { data, code } = res;
          if (code === 200) {
            this.templateUrl = data.relationCertImageUrl;
          } else {
            this.$toast("模板获取失败，请联系客服");
          }
        });
      }
    },
    async isBlackListMethods(val, message) {
      if (!val) return false;
      const { data } = await isBlacklist(val);
      try {
        if (data.isBlacklist) {
          let msg = data.consumerHotline
            ? `${message}填写失败，代码1000，请联系客服${data.consumerHotline}`
            : `${message}填写失败，代码1000`;
          let doms = document.getElementsByClassName("van-toast")[0];
          if (
            doms == undefined ||
            (doms.style && doms.style.display == "none")
          ) {
            this.$toast(msg);
          }
          return true;
        } else {
          return false;
        }
      } catch (error) {
        console.error(error);
        return false;
      }
    },
    validator(val) {
      const check = val.filter((item) => item.url);
      return check.length > 0;
    },
  },
};
</script>
<style scoped lang="less">
.container {
  overflow: hidden;
}
.content-box {
  height: calc(100vh - 120px);
  overflow-y: scroll;
}

/deep/.van-field__label {
  color: #323233;
}
/deep/.van-dialog__content {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 57px 0;
}

.next-step-btn {
  width: 80%;
  margin: 50px auto;
}
.app {
  background: #f9f9f9;
}
.content-box {
  background: #f9f9f9;
  padding-bottom: 1px;
  box-sizing: border-box;
}

.mt-margin {
  margin-top: 24px;
}
.example-container {
  padding: 0 100px;
  max-height: 60vh;
  overflow-y: scroll;
}
.example-container::-webkit-scrollbar {
  display: none;
}
.example-img {
  width: 100%;
  height: 100%;
}
.attach-item {
  margin-top: 24px;
  background: #fff;
  padding: 35px 32px;
  p.attach-item-title {
    font-size: 30px;
    font-weight: 400;
    color: #131313;
  }
}
.upload-title {
  text-align: left;
  font-size: 30px;
  font-weight: 400;
  color: #131313;
  width: calc(100vw - 64px);
}
.upload-content {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  width: calc(100vw - 64px);
  flex-wrap: wrap;
  .attach-label {
    width: 45%;
    padding-left: 5px;
  }
  .upload-item {
    width: auto;
    min-height: 220px;
    padding: 10px 0;
  }
}
.placholder {
  font-size: 28px;
  font-weight: 400;
  color: #131313;
  margin: 12px 0;
  text-align: center;
  opacity: 0.8;
  max-width: 300px;
}
.example {
  display: flex;
  align-items: center;
  color: #ffb72f;
  justify-content: center;
}
.notes {
  font-size: 28px;
  font-weight: 400;
  color: #131313;
  opacity: 0.7;
  padding: 24px 35px 0;
  line-height: 35px;
}
/deep/.van-nav-bar__title {
  font-size: 36px !important;
}
/deep/ .van-nav-bar__text {
  color: #ffb72f !important;
}
/deep/ .van-nav-bar__content {
  height: 110px !important;
}
/deep/ .van-field__label {
  width: auto !important;
}
.upload-container {
  overflow: unset;
}
.preview-img {
  width: 325px;
  height: 215px;
  margin: 0 16px 16px 0;
}
</style>

